package com.dapeis.web.wx.controller.impl;

import java.security.InvalidParameterException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

import com.ag.core.base.Pager;
import com.ag.core.exception.SysTipsException;
import com.ag.core.utils.AgAssert;
import com.ag.utils.DictionarySettingUtils;
import com.ag.utils.json.AGsonBuilder;
import com.dapeis.core.utils.DBConfigUtils;
import com.dapeis.core.utils.StylistConfig;
import com.dapeis.core.utils.StylistConstants;
import com.dapeis.domain.Garderobe;
import com.dapeis.domain.ext.GarderobeExt;
import com.dapeis.exception.StateDisableException;
import com.dapeis.service.COSFileService;
import com.dapeis.service.GarderobeService;
import com.dapeis.web.wx.controller.IGarderobeController;
import com.dapeis.web.wx.controller.RestController;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;

/**
 * 衣橱 Title:GarderobeImplCotrolle.java GarderobeImplCotrolle Description:
 * 
 * @author yuanyong
 * @date 2017年5月3日 下午2:48:49 Email: hzyuanyong@126.com
 *
 */
@Controller
@RequestMapping("/wx/garderobe")
public class GarderobeImplCotrolle extends RestController implements
	IGarderobeController {

    @Resource
    COSFileService cosFileService;

    @Resource
    GarderobeService garderobeService;

    @Override
    public JsonElement add(@RequestParam String name,
	    @RequestParam String remark, @RequestParam String typeCode,
	    @RequestParam MultipartFile img, HttpServletRequest request) {
	if (StringUtils.isNotBlank(typeCode) && null != img
		&& checkParamSetting(typeCode)) {
	    String imgPath = cosFileService.saveFile(img,
		    StylistConstants.UploadType.GARDEROBE, request);
	    if (null != imgPath) {
		Garderobe garderobe = new Garderobe();
		garderobe.setImgUrl(imgPath);
		garderobe.setCreateTime(new Date().getTime() / 1000);
		garderobe.setName(name);
		garderobe.setRemark(remark);
		garderobe.setTypeCode(typeCode);
		garderobe.setType(StylistConstants.GarderobeType.USER);
		garderobe.setUserId(getThreadLocalUserId());
		garderobeService.insert(garderobe);
		JsonObject json = success();
		json.add("garderobe",
			AGsonBuilder.create().toJsonTree(garderobe));
		json.addProperty("typeCode", typeCode);
		json.addProperty("typeName", getParamValue(typeCode));
		return json;
	    }
	}
	throw new InvalidParameterException("未上传图片");
    }

    @Override
    public @ResponseBody JsonElement delete(@RequestParam Long gid,
	    HttpServletRequest request) {
	Garderobe garderobe = garderobeService.selectByPrimaryKey(gid);
	AgAssert.notNull(garderobe, SysTipsException.class, "查询不到衣橱信息ID:" + gid);
	AgAssert.isTrue(garderobe.getState() != StylistConstants.State.DISABLE,
		StateDisableException.class);
	garderobe.setState(StylistConstants.State.DISABLE);
	garderobeService.updateByPrimaryKeySelective(garderobe);
	JsonObject json = success();
	return json;
    }

    @Override
    public @ResponseBody JsonElement list(HttpServletRequest request) {
	// 获取用户信息

	Pager pager = new Pager();
	// 查询所有
	pager.setPageSize(10000);
	Example example = new Example(Garderobe.class);
	Criteria criteria = example.createCriteria();
	criteria.andEqualTo(Garderobe.PROPERTY_USERID, getThreadLocalUserId());
	criteria.andEqualTo(Garderobe.PROPERTY_STATE,
		StylistConstants.State.NORMAL);
	criteria.andEqualTo(Garderobe.PROPERTY_TYPE,
		StylistConstants.GarderobeType.USER);
	example.orderBy(Garderobe.PROPERTY_TYPECODE).asc();
	pager.setExample(example);
	garderobeService.pager(pager);
	List<Garderobe> list = pager.getItemList();
	// 获取所有分类列表
	Map<String, String> typeMap = DictionarySettingUtils
		.getParameterMap(StylistConfig.GARDEOROBE_CONFIG);

	List<GarderobeExt> resultList = new ArrayList<GarderobeExt>();
	for (String k : typeMap.keySet()) {
	    List<Garderobe> temp = new ArrayList<Garderobe>();
	    for (Garderobe ga : list) {
		if (ga.getTypeCode().equals(k)) {
		    temp.add(ga);
		}
	    }
	    if (!temp.isEmpty()) {
		GarderobeExt garderobeExt = new GarderobeExt();
		garderobeExt.setGarderobes(temp);
		garderobeExt.setTypeCode(k);
		garderobeExt.setTypeName(getParamValue(k));
		resultList.add(garderobeExt);
	    }
	}
	JsonObject resultJsonObject = success();
	JsonArray jsonArray = new JsonArray();
	for (GarderobeExt ext : resultList) {
	    JsonObject json = new JsonObject();
	    json.addProperty("typeCode", ext.getTypeCode());
	    json.addProperty("typeName", ext.getTypeName());
	    json.add("list",
		    AGsonBuilder.create().toJsonTree(ext.getGarderobes()));
	    jsonArray.add(json);
	}
	resultJsonObject.add("list", jsonArray);
	return resultJsonObject;
    }

    @Override
    public @ResponseBody JsonElement detail(@RequestParam Long gid,
	    HttpServletRequest request) {
	Garderobe garderobe = garderobeService.selectByPrimaryKey(gid);
	AgAssert.notNull(garderobe, SysTipsException.class, "查询不到衣橱信息ID:" + gid);
	AgAssert.isTrue(garderobe.getState() != StylistConstants.State.DISABLE,
		StateDisableException.class);
	JsonObject json = success();
	json.addProperty("typeCode", garderobe.getTypeCode());
	json.addProperty("typeName", getParamValue(garderobe.getTypeCode()));
	// 此处应前端要求，独立到外层
	json.addProperty("id", garderobe.getId());
	json.addProperty("name", garderobe.getName());
	json.addProperty("remark", garderobe.getRemark());
	json.addProperty("imgUrl",
		DBConfigUtils.getFullImgPath(garderobe.getImgUrl()));

	return json;

    }

    @Override
    public @ResponseBody JsonElement modify(@RequestParam Long gid,
	    @RequestParam String name, @RequestParam String remark,
	    @RequestParam String typeCode,
	    @RequestParam(required = false) MultipartFile img,
	    HttpServletRequest request) {
	Garderobe garderobe = garderobeService.selectByPrimaryKey(gid);
	AgAssert.notNull(garderobe, SysTipsException.class, "查询不到衣橱信息ID:" + gid);
	AgAssert.isTrue(garderobe.getState() != StylistConstants.State.DISABLE,
		StateDisableException.class);
	garderobe.setName(name);
	garderobe.setRemark(remark);
	garderobe.setTypeCode(typeCode);
	if (null != img && img.getSize() > 10) {
	    String filePath = cosFileService.saveFile(img,
		    StylistConstants.UploadType.GARDEROBE, request);
	    if (null != filePath) {
		garderobe.setImgUrl(filePath);
	    }
	}
	garderobeService.updateByPrimaryKeySelective(garderobe);
	JsonObject json = success();
	return json;
    }

    /**
     * 检查前端传回来的参数是否已经配置
     * 
     * @return
     */
    public boolean checkParamSetting(String typeCode) {
	Map<String, String> typeMap = DictionarySettingUtils
		.getParameterMap(StylistConfig.GARDEOROBE_CONFIG);
	boolean isContain = typeMap.containsKey(typeCode);
	if (!isContain) {
	    return false;
	}
	return true;
    }

    public String getParamValue(String typeCode) {
	return DictionarySettingUtils
		.getParameterValue(StylistConfig.GARDEOROBE_CONFIG + "."
			+ typeCode);
    }

}
